package com.example.servlet.auth;

import com.example.entity.User;
import com.example.service.ManagerService;
import com.example.service.UserService;
import com.example.service.impl.ManagerServiceImpl;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.BCryptUtil;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.IOException;

@WebServlet("/user_login")
public class LoginServlet extends HttpServlet {

    private UserService service;
    private SqlSession sqlSession;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new UserServiceImpl(sqlSession);
    }

    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            String u_account = null;
            String u_password = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("u_account")) u_account = cookie.getValue();
                if (cookie.getName().equals("u_password")) u_password = cookie.getValue();

            }
            if (u_account != null && u_password != null) {
                String storedHashedPassword = service.getHashedPasswordByAccount(u_account);
                if(storedHashedPassword != null){
                    boolean isPasswordCorrect = BCryptUtil.verifyPassword(u_password, storedHashedPassword);
                    if(isPasswordCorrect){
                        // 登录校验
                        if (service.auth(u_account, storedHashedPassword, req.getSession())) {
                            resp.sendRedirect("user_index");
                            return;
                        }
                    }
                }
            }
        }
        Context context = new Context();
        if (req.getSession().getAttribute("user_login_failure") != null) {
            context.setVariable("user_login_failure", true);
            req.getSession().removeAttribute("user_login_failure");
        }
        if (req.getSession().getAttribute("register-success") != null) {
            context.setVariable("registerSuccess", true);
            req.getSession().removeAttribute("register-success");
        }
        if (req.getSession().getAttribute("unsubscribe-success") != null) {
            context.setVariable("unsubscribeSuccess", true);
            req.getSession().removeAttribute("unsubscribe-success");
        }
        if (req.getSession().getAttribute("user") != null) {
            resp.sendRedirect("user_index");
            return;
        }
        ThymeleafUtil.process("user_login.html", context, resp.getWriter());
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try (SqlSession newSession = MybatisUtil.getSession()) {
            UserService freshService = new UserServiceImpl(newSession);
            String u_account = req.getParameter("u_account");
            String u_password = req.getParameter("u_password");
            String remember = req.getParameter("remember-me");

            if(service.isExistByAccount(u_account)==0){
                req.getSession().setAttribute("user_login_failure", new Object());
                this.doGet(req, resp);
                return;
            }
            // 从数据库中获取存储的哈希密码
            String storedHashedPassword = freshService.getHashedPasswordByAccount(u_account);
            if (storedHashedPassword != null) {
                // 使用 BCryptUtil 验证密码
                boolean isPasswordCorrect = BCryptUtil.verifyPassword(u_password, storedHashedPassword);

                if (isPasswordCorrect) {
                    if (freshService.auth(u_account, storedHashedPassword, req.getSession())) {
                        if (remember != null) {
                            Cookie cookie_u_account = new Cookie("u_account", u_account);
                            cookie_u_account.setMaxAge(60 * 60 * 24);
                            Cookie cookie_u_password = new Cookie("u_password", u_password);
                            cookie_u_password.setMaxAge(60 * 60 * 24);
                            resp.addCookie(cookie_u_account);
                            resp.addCookie(cookie_u_password);
                        }
                        resp.sendRedirect("user_index");
                    } else {
                        req.getSession().setAttribute("user_login_failure", new Object());
                        this.doGet(req, resp);
                    }
                } else {
                    req.getSession().setAttribute("user_login_failure", new Object());
                    this.doGet(req, resp);
                }
            } else {
                req.getSession().setAttribute("user_login_failure", new Object());
                this.doGet(req, resp);
            }
        }
/*

            if (service.auth(u_account, u_password, req.getSession())) {
                if (remember != null) {
                    Cookie cookie_m_account = new Cookie("u_account", u_account);
                    cookie_m_account.setMaxAge(60 * 60 * 24);
                    Cookie cookie_m_password = new Cookie("u_password", u_password);
                    cookie_m_password.setMaxAge(60 * 60 * 24);
                    resp.addCookie(cookie_m_account);
                    resp.addCookie(cookie_m_password);
                }
                resp.sendRedirect("user_index");
            } else {
                req.getSession().setAttribute("user_login_failure", new Object());
                this.doGet(req, resp);
            }
        }
*/

    }
}
